package com.example.testdb1.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.testdb1.entity.result.R;
import com.example.testdb1.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器初始化完成");
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;

        String requestURL = servletRequest.getRequestURL().toString();
        //1.如果是登录请求，直接放行
        //todo swagger请求放行怎么设置
        if (requestURL.contains("/login") || requestURL.contains("/doc.html")) {
            return true;
        }
        //2.jwt是否存在,不存在，返回错误状态码
        String token = servletRequest.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            log.error("令牌解析失败");

            R<Object> result = R.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(result);
            servletResponse.setContentType("application/json;charset=utf-8");
            servletResponse.getWriter().write(jsonString);
            return false;
        }
        //3.校验jwt是否有效
        try {
            JwtUtils.resolveJwt(token);
        } catch (Exception e) {
            log.error("令牌解析失败");

            R<Object> result = R.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(result);
            servletResponse.setContentType("application/json;charset=utf-8");
            servletResponse.getWriter().write(jsonString);
            return false;
        }

        //4.放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器到了请求，做了简单处理");


        System.out.println("拦截器到了请求后，做了简单处理");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器销毁");
        // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
